package com.vids.controller;

import cn.hutool.core.collection.CollUtil;
import com.vids.utils.StringUtils;
import com.vids.alarm.ApeTask;
import com.vids.constant.Urlconstant;
import com.vids.constant.VIIDRespEnum;
import com.vids.alarm.MyRejected;

import com.vids.model.entity.Face;
import com.vids.model.entity.ImageBusiness;
import com.vids.model.param.FaceBatchParam;
import com.vids.model.param.FaceParam;
import com.vids.model.param.SubImageBatchParam;
import com.vids.model.param.FaceModel;
import com.vids.model.response.FaceBatch;
import com.vids.model.response.ResponseStatus;
import com.vids.model.vo.SubImageInfoVo;
import com.vids.service.IFaceService;
import com.vids.service.IImageBusinessService;
import com.vids.utils.AlarmUtils;
import com.vids.utils.BeanUtilss;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.vids.utils.BussinessIDGennelUtil;
import com.vids.utils.ImageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 人像 前端控制器
 * </p>
 *
 */
@Slf4j
@RestController
@RequestMapping("/VIID")
@RequiredArgsConstructor
public class FaceController {

    public final static String fCode = "02";
    public final static String cCode = "06";

    public final static String type = "11";

    private String appId = "42010000005040000000";

    private final IFaceService iTBigDataFaceService;

    private final IImageBusinessService imageBusinessService;

//    private Map<String,Long> map = AlarmUtils.newMap(); 未用到 edward 注掉
    private String endTime;

    // 线程池
    ThreadPoolExecutor pool;

    {
        try {
            pool = new ThreadPoolExecutor(
                            15,
                            20,
                            60,
                            TimeUnit.SECONDS,
                            new LinkedBlockingQueue<Runnable>()
                            , new MyRejected()
                    );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

  /*  // 连接sdk,并部署合约
    private static String path = "/mount/data1/jar/config.toml";

    private static TransactionCallbackMock faceCallbackMock;  // 用来封存交易回执的对象 face
    private static AssembleTransactionProcessor transactionProcessor;

    static {
        // 异步部署合约
        try {
            BcosSDK sdk = BcosSDK.build(path);
            Client client = sdk.getClient(1); //  获取群组1的客户端
            CryptoKeyPair cryptoKeyPair = client.getCryptoSuite().getCryptoKeyPair();  // 密钥
            //transactionProcessor = TransactionProcessorFactory.createAssembleTransactionProcessor(client, cryptoKeyPair, "src/main/resources/abi/", "src/main/resources/bin/");
            //transactionProcessor = TransactionProcessorFactory.createAssembleTransactionProcessor(client, cryptoKeyPair, "C:\\Users\\gaoyang\\Desktop\\abi\\", "C:\\Users\\gaoyang\\Desktop\\bin\\");
            transactionProcessor = TransactionProcessorFactory.createAssembleTransactionProcessor(client, cryptoKeyPair, "/mount/data1/jar/abi/", "/mount/data1/jar/bin/");
            faceCallbackMock = new TransactionCallbackMock();
            transactionProcessor.deployByContractLoaderAsync("Face", new ArrayList<Object>(), faceCallbackMock);  // 异步部署Face合约
        } catch (ABICodecException e) {
            log.error("FaceController中初始化部署合约出现的错误",e);
        } catch (NoSuchTransactionFileException e) {
            log.error("FaceController中初始化部署合约出现的错误",e);
        } catch (Exception e) {
            log.error("FaceController中初始化部署合约出现的错误",e);
        }
    }*/

   /* static String property;
   static {
       InputStream inputStream = null;
       try {
           inputStream = new BufferedInputStream(new FileInputStream("/mount/data1/jar/convert.properties"));
           Properties properties = new Properties();
           properties.load(inputStream);
            property = properties.getProperty("switch");
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }


   }*/





    /**
     * 校验参数
     *
     * @param status
     */
    private void validateParams(Face tBigDataFace, ResponseStatus status) {
	StringBuffer sb = new StringBuffer();
	if (StringUtils.isEmpty(tBigDataFace.getFaceID())) {
	    sb.append("FaceID必填；");
	}
	if (tBigDataFace.getInfoKind() == null) {
	    sb.append("InfoKind必填；");
	}
	if (StringUtils.isEmpty(tBigDataFace.getSourceID())) {
	    sb.append("SourceID必填；");
	}
	if (tBigDataFace.getIsSuspectedTerrorist() == null) {
	    sb.append("IsSuspectedTerrorist必填；");
	}
	if (tBigDataFace.getIsCriminalInvolved() == null) {
	    sb.append("IsCriminalInvolved必填；");
	}
	if (tBigDataFace.getIsDetainees() == null) {
	    sb.append("IsDetainees必填；");
	}
	if (tBigDataFace.getIsVictim() == null) {
	    sb.append("IsVictim必填；");
	}
	if (tBigDataFace.getIsSuspiciousPerson() == null) {
	    sb.append("IsSuspiciousPerson必填；");
	}
	if (tBigDataFace.getInfoKind() != null && tBigDataFace.getInfoKind() == 1) {
	    if (StringUtils.isEmpty(tBigDataFace.getDeviceID())) {
		sb.append("自动采集时，DeviceID必填；");
	    }
	    if (tBigDataFace.getLeftTopX() == null) {
		sb.append("自动采集时，LeftTopX必填；");
	    }
	    if (tBigDataFace.getLeftTopY() == null) {
		sb.append("自动采集时，LeftTopY必填；");
	    }
	    if (tBigDataFace.getRightBtmX() == null) {
		sb.append("自动采集时，RightBtmX必填；");
	    }
	    if (tBigDataFace.getRightBtmY() == null) {
		sb.append("自动采集时，RightBtmY必填；");
	    }
	}
	if (tBigDataFace.getLeftTopX() != null && !tBigDataFace.getLeftTopX().toString().matches("^[0-9]+$")) {
	    sb.append("LeftTopX字段为数字；");
	}
	if (tBigDataFace.getLeftTopY() != null && !tBigDataFace.getLeftTopY().toString().matches("^[0-9]+$")) {
	    sb.append("LeftTopY字段为数字；");
	}
	if (tBigDataFace.getRightBtmX() != null && !tBigDataFace.getRightBtmX().toString().matches("^[0-9]+$")) {
	    sb.append("RightBtmX字段为数字；");
	}
	if (tBigDataFace.getRightBtmY() != null && !tBigDataFace.getRightBtmY().toString().matches("^[0-9]+$")) {
	    sb.append("RightBtmY字段为数字；");
	}
	if (tBigDataFace.getInfoKind() != null && tBigDataFace.getInfoKind() == 2) {
	    if (tBigDataFace.getLocationMarkTime() == null) {
		sb.append("人工采集时，LocationMarkTime必填；");
	    }
	}
	if (!StringUtils.isEmpty(tBigDataFace.getFaceID())) {
	    if (tBigDataFace.getFaceID().length() != 48) {
		sb.append("FaceID字段长度不为48；");
	    }
	    if (!tBigDataFace.getFaceID().matches("^[0-9]+$")) {
		sb.append("FaceID字段为纯数字；");
	    }
	}
	if (!StringUtils.isEmpty(tBigDataFace.getSourceID())) {
	    if (tBigDataFace.getSourceID().length() != 41) {
		sb.append("SourceID字段长度不为41；");
	    }
	    if (!tBigDataFace.getSourceID().matches("^[0-9]+$")) {
		sb.append("SourceID字段为纯数字；");
	    }
	}
	if (!StringUtils.isEmpty(tBigDataFace.getDeviceID())) {
	    if (tBigDataFace.getDeviceID().length() != 20) {
		sb.append("DeviceID字段长度不为20；");
	    }
	    if (!tBigDataFace.getDeviceID().matches("^[0-9]+$")) {
		sb.append("DeviceID字段为纯数字；");
	    }
	}
	if (!StringUtils.isEmpty(tBigDataFace.getNativeCityCode())) {
	    if (tBigDataFace.getNativeCityCode().length() != 6) {
		sb.append("NativeCityCode字段长度不为6；");
	    }
	    if (!tBigDataFace.getNativeCityCode().matches("^[0-9]+$")) {
		sb.append("NativeCityCode字段为纯数字；");
	    }
	}
	if (!StringUtils.isEmpty(tBigDataFace.getResidenceAdminDivision())) {
	    if (tBigDataFace.getResidenceAdminDivision().length() != 6) {
		sb.append("ResidenceAdminDivision字段长度不为6；");
	    }
	    if (!tBigDataFace.getResidenceAdminDivision().matches("^[0-9]+$")) {
		sb.append("ResidenceAdminDivision字段为纯数字；");
	    }
	}
	if (!StringUtils.isEmpty(tBigDataFace.getEscapedCriminalNumber())
		&& tBigDataFace.getEscapedCriminalNumber().length() != 23) {
	    sb.append("EscapedCriminalNumber字段长度不为23；");
	}
	if (!StringUtils.isEmpty(tBigDataFace.getSuspectedTerroristNumber())
		&& tBigDataFace.getSuspectedTerroristNumber().length() != 19) {
	    sb.append("SuspectedTerroristNumber字段长度不为19；");
	}
	if (!StringUtils.isEmpty(tBigDataFace.getIDType()) && tBigDataFace.getIDType().length() != 3) {
	    sb.append("IDType字段长度不为3；");
	}
	if (!StringUtils.isEmpty(tBigDataFace.getEthicCode()) && tBigDataFace.getEthicCode().length() != 2) {
	    sb.append("EthicCode字段长度不为2；");
	}
	if (!StringUtils.isEmpty(tBigDataFace.getNationalityCode())
		&& tBigDataFace.getNationalityCode().length() != 3) {
	    sb.append("NationalityCode字段长度不为3；");
	}
	// ChineseAccentCode 6
	if (!StringUtils.isEmpty(tBigDataFace.getChineseAccentCode())
		&& tBigDataFace.getChineseAccentCode().length() != 6) {
	    sb.append("ChineseAccentCode字段长度不为6；");
	}
	if (!StringUtils.isEmpty(tBigDataFace.getJobCategory()) && tBigDataFace.getJobCategory().length() != 3) {
	    sb.append("JobCategory字段长度不为3；");
	}
	// FaceStyle 4
	if (!StringUtils.isEmpty(tBigDataFace.getFaceStyle()) && tBigDataFace.getFaceStyle().length() != 4) {
	    sb.append("FaceStyle字段长度不为4；");
	}
	// FacialFeature <40
	if (!StringUtils.isEmpty(tBigDataFace.getFacialFeature()) && tBigDataFace.getFacialFeature().length() > 40) {
	    sb.append("FacialFeature字段长度不能大于40；");
	}
	// PhysicalFeature < 200
	if (!StringUtils.isEmpty(tBigDataFace.getFacialFeature()) && tBigDataFace.getFacialFeature().length() > 200) {
	    sb.append("FacialFeature字段长度不能大于200；");
	}
	// ImmigrantTypeCode 2
	if (!StringUtils.isEmpty(tBigDataFace.getImmigrantTypeCode())
		&& tBigDataFace.getImmigrantTypeCode().length() != 2) {
	    sb.append("ImmigrantTypeCode字段长度不为2；");
	}
	// CriminalInvolvedSpecilisationCode 2
	if (!StringUtils.isEmpty(tBigDataFace.getCriminalInvolvedSpecilisationCode())
		&& tBigDataFace.getCriminalInvolvedSpecilisationCode().length() != 2) {
	    sb.append("CriminalInvolvedSpecilisationCode字段长度不为2；");
	}
	// BodySpeciallMark 7
	if (!StringUtils.isEmpty(tBigDataFace.getBodySpeciallMark())
		&& tBigDataFace.getBodySpeciallMark().length() != 7) {
	    sb.append("BodySpeciallMark字段长度不为7；");
	}
	// CrimeMethod 4
	if (!StringUtils.isEmpty(tBigDataFace.getCrimeMethod()) && tBigDataFace.getCrimeMethod().length() != 4) {
	    sb.append("CrimeMethod字段长度不为4；");
	}
	// CrimeCharacterCode 3
	if (!StringUtils.isEmpty(tBigDataFace.getCrimeCharacterCode())
		&& tBigDataFace.getCrimeCharacterCode().length() != 3) {
	    sb.append("CrimeCharacterCode字段长度不为3；");
	}
	// DetaineesSpecialIdentity 2
	if (!StringUtils.isEmpty(tBigDataFace.getDetaineesSpecialIdentity())
		&& tBigDataFace.getDetaineesSpecialIdentity().length() != 2) {
	    sb.append("DetaineesSpecialIdentity字段长度不为2；");
	}
	// MemberTypeCode 2
	if (!StringUtils.isEmpty(tBigDataFace.getMemberTypeCode()) && tBigDataFace.getMemberTypeCode().length() != 2) {
	    sb.append("MemberTypeCode字段长度不为2；");
	}
	// VictimType 3
	if (!StringUtils.isEmpty(tBigDataFace.getVictimType()) && tBigDataFace.getVictimType().length() != 3) {
	    sb.append("VictimType字段长度不为3；");
	}
	// CorpseConditionCode 2
	if (!StringUtils.isEmpty(tBigDataFace.getCorpseConditionCode())
		&& tBigDataFace.getCorpseConditionCode().length() != 2) {
	    sb.append("CorpseConditionCode字段长度不为2；");
	}
	// Name <50
	if (!StringUtils.isEmpty(tBigDataFace.getName()) && tBigDataFace.getName().length() > 50) {
	    sb.append("Name字段长度不能大于50；");
	}
	// UsedName <50
	if (!StringUtils.isEmpty(tBigDataFace.getUsedName()) && tBigDataFace.getUsedName().length() > 50) {
	    sb.append("UsedName字段长度不能大于50；");
	}
	// Alias <50
	if (!StringUtils.isEmpty(tBigDataFace.getAlias()) && tBigDataFace.getAlias().length() > 50) {
	    sb.append("Alias字段长度不能大于50；");
	}

	if (!StringUtils.isEmpty(tBigDataFace.getEyebrowStyle()) && tBigDataFace.getEyebrowStyle().length() > 32) {
	    sb.append("EyebrowStyle字段长度不能大于32；");
	}
	if (!StringUtils.isEmpty(tBigDataFace.getNoseStyle()) && tBigDataFace.getNoseStyle().length() > 32) {
	    sb.append("NoseStyle字段长度不能大于32；");
	}
	if (!StringUtils.isEmpty(tBigDataFace.getMustacheStyle()) && tBigDataFace.getMustacheStyle().length() > 32) {
	    sb.append("MustacheStyle字段长度不能大于32；");
	}
	if (!StringUtils.isEmpty(tBigDataFace.getLipStyle()) && tBigDataFace.getLipStyle().length() > 32) {
	    sb.append("LipStyle字段长度不能大于32；");
	}
	if (!StringUtils.isEmpty(tBigDataFace.getWrinklePouch()) && tBigDataFace.getWrinklePouch().length() > 32) {
	    sb.append("WrinklePouch字段长度不能大于32；");
	}
	if (!StringUtils.isEmpty(tBigDataFace.getAcneStain()) && tBigDataFace.getAcneStain().length() > 32) {
	    sb.append("AcneStain字段长度不能大于32；");
	}
	if (!StringUtils.isEmpty(tBigDataFace.getFreckleBirthmark())
		&& tBigDataFace.getFreckleBirthmark().length() > 32) {
	    sb.append("FreckleBirthmark字段长度不能大于32；");
	}
	if (!StringUtils.isEmpty(tBigDataFace.getScarDimple()) && tBigDataFace.getScarDimple().length() > 32) {
	    sb.append("ScarDimple字段长度不能大于32；");
	}
	if (!StringUtils.isEmpty(tBigDataFace.getOtherFeature()) && tBigDataFace.getOtherFeature().length() > 32) {
	    sb.append("OtherFeature字段长度不能大于32；");
	}
	// DetentionHouseCode =9
	if (!StringUtils.isEmpty(tBigDataFace.getDetentionHouseCode())
		&& tBigDataFace.getDetentionHouseCode().length() != 9) {
	    sb.append("DetentionHouseCode字段长度不为9；");
	}
	// IDNumber 30
	if (!StringUtils.isEmpty(tBigDataFace.getIDNumber()) && tBigDataFace.getIDNumber().length() > 30) {
	    sb.append("IDNumber字段长度不能大于30；");
	}
	// Attitude 1：平视；2：微仰；3：微俯；4：左微侧脸；5：左斜侧脸；6：左全侧脸；7：右微侧脸；8：右斜侧脸；9：右全侧脸
	if (tBigDataFace.getAttitude() != null
		&& !Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9).contains(tBigDataFace.getAttitude())) {
	    sb.append("Attitude的值不正确，Attitude为，1：平视；2：微仰；3：微俯；4：左微侧脸；5：左斜侧脸；6：左全侧脸；7：右微侧脸；8：右斜侧脸；9：右全侧脸；");
	}
	// Similaritydegree 人脸相似度，[0，1]
	if (tBigDataFace.getSimilaritydegree() != null) {
	    if (new BigDecimal(tBigDataFace.getSimilaritydegree()).compareTo(new BigDecimal("0")) == -1
		    || new BigDecimal(tBigDataFace.getSimilaritydegree()).compareTo(new BigDecimal("1")) == 1) {
		sb.append("Similaritydegree的值不正确，人脸相似度，[0，1]；");
	    }
	}
	if (tBigDataFace.getIsDriver() != null && !Arrays.asList(0, 1, 2).contains(tBigDataFace.getIsDriver())) {
	    sb.append("IsDriver的值不正确，IsDriver为，0：否；1：是；2：不确定；");
	}
	if (tBigDataFace.getIsForeigner() != null && !Arrays.asList(0, 1, 2).contains(tBigDataFace.getIsForeigner())) {
	    sb.append("IsForeigner的值不正确，IsForeigner为，0：否；1：是；2：不确定；");
	}
	if (tBigDataFace.getIsSuspectedTerrorist() != null
		&& !Arrays.asList(0, 1, 2).contains(tBigDataFace.getIsSuspectedTerrorist())) {
	    sb.append("IsSuspectedTerrorist的值不正确，IsSuspectedTerrorist为，0：否；1：是；2：不确定；");
	}
	if (tBigDataFace.getIsCriminalInvolved() != null
		&& !Arrays.asList(0, 1, 2).contains(tBigDataFace.getIsCriminalInvolved())) {
	    sb.append("IsCriminalInvolved的值不正确，IsCriminalInvolved为，0：否；1：是；2：不确定；");
	}
	if (tBigDataFace.getIsDetainees() != null && !Arrays.asList(0, 1, 2).contains(tBigDataFace.getIsDetainees())) {
	    sb.append("IsDetainees的值不正确，IsDetainees为，0：否；1：是；2：不确定；");
	}
	if (tBigDataFace.getIsVictim() != null && !Arrays.asList(0, 1, 2).contains(tBigDataFace.getIsVictim())) {
	    sb.append("IsVictim的值不正确，IsVictim为，0：否；1：是；2：不确定；");
	}
	if (tBigDataFace.getIsSuspiciousPerson() != null
		&& !Arrays.asList(0, 1, 2).contains(tBigDataFace.getIsSuspiciousPerson())) {
	    sb.append("IsSuspiciousPerson的值不正确，IsSuspiciousPerson为，0：否；1：是；2：不确定；");
	}

	if (sb != null && !StringUtils.isEmpty(sb.toString())) {
	    setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, sb.toString());
	}
    }

	//ApeTask apeTask = new ApeTask(map, endTime, faceModel);
	//pool.execute(apeTask);

               /* try {

                    // 创建回调类的实例
                    TransactionCallbackMock faceRespCallbackMock = new TransactionCallbackMock();

                    // 定义构造参数
                    //faceID,infoKind,sourceID,deviceID,faceAppearTime
                    List<Object> faceParams = Lists.newArrayList();
                    faceParams.add(faceModel.getFaceID());
                    faceParams.add(faceModel.getInfoKind().toString());
                    faceParams.add(faceModel.getSourceID());
                    faceParams.add(faceModel.getDeviceID());
                    faceParams.add(faceModel.getFaceAppearTime());

                    String abi = "[{\"constant\":false,\"inputs\":[{\"name\":\"faceID\",\"type\":\"string\"},{\"name\":\"infoKind\",\"type\":\"string\"},{\"name\":\"sourceID\",\"type\":\"string\"},{\"name\":\"deviceID\",\"type\":\"string\"},{\"name\":\"faceAppearTime\",\"type\":\"string\"}],\"name\":\"insert\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"count\",\"type\":\"int256\"}],\"name\":\"CreateResult\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"count\",\"type\":\"int256\"}],\"name\":\"InsertResult\",\"type\":\"event\"}]";
                    // 异步调用合约交易
                    transactionProcessor.sendTransactionAsync(transactionReceipt.getContractAddress(), abi, "insert", faceParams, faceRespCallbackMock );  // 第一个参数：合约地址 第二个：合约abi字符串  第三个：合约中的函数名  第四个：上链时所需要的参数   第五个：存储执行信息
                    TransactionReceipt respTransactionReceipt = faceRespCallbackMock.getResult();  // 回执
                    if(respTransactionReceipt.getTransactionHash()==null){
                        log.error("采集人脸数据上链失败！！");
                    }
                }catch (Exception e){
                    //System.out.println(e);
                    log.error("采集人脸数据上链时出现的异常",e);
                }
*/
	//                if(property.equals("true")){

	//                }

	/**
     * 批量新增
     *
     * @param param
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/Faces", produces = "application/VIID+JSON")
    public Object postList(@RequestBody FaceBatchParam param) throws Exception
	{
		List<ResponseStatus> resps = new ArrayList<ResponseStatus>();
		if (param == null || param.getFaceListObject() == null || param.getFaceListObject().getFaceObject() == null
			|| param.getFaceListObject().getFaceObject().size() == 0) {
			ResponseStatus status = new ResponseStatus(Urlconstant.URL_BIG_DATA_15, VIIDRespEnum.OK.getCode(),
				new Date());
			setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数为空；");
			resps.add(status);
			return new ResponseEntity<Map<String, Object>>(
				BeanUtilss.objectToMap(BeanUtilss.getBatchResponseModel(resps)), HttpStatus.CREATED);
		}

		List<FaceModel> list = param.getFaceListObject().getFaceObject();

        if (CollUtil.isNotEmpty(list))
		{
            //TransactionReceipt transactionReceipt = faceCallbackMock.getResult();   // 部署合约的回执信息
//            log.info("人脸保存开始");

			for (FaceModel faceModel: list)
			{

				List<SubImageInfoVo> subImageInfoObject = faceModel.getSubImageList().getSubImageInfoObject();
//				log.info("Face Data=======: "+subImageInfoObject.get(0).getData());
//				log.info("Face Data not null." );

//				for (SubImageInfoVo subImageInfoVo: subImageInfoObject) {
//log.info("FaceZMC"+subImageInfoVo.getImageID());
//					//原来第二个参数：faceModel.getFaceID()						ImageUtil.convertBase64ToImageAndSave(subImageInfoVo.getData(),faceModel.getDeviceID(),subImageInfoVo.getImageID(),"face");
//				}
            }
//            log.info("人脸保存结束");
        }

//		commonSaveFaceBatchModel(resps, list);
		return new ResponseEntity<Map<String, Object>>(BeanUtilss.objectToMap(BeanUtilss.getBatchResponseModel(resps)),
		HttpStatus.CREATED);
    }

    public void commonSaveFaceBatchModel(List<ResponseStatus> resps, List<FaceModel> list) {
		for (FaceModel model : list) {
			ResponseStatus status = new ResponseStatus(Urlconstant.URL_BIG_DATA_15, VIIDRespEnum.OK.getCode(),
				new Date());

			if (model == null) {
				setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数为空；");
				resps.add(status);
				continue;
			}

			FaceBatch face = BeanUtilss.transferObjectCommon(model, FaceBatch.class);
			if (model.getSubImageList() != null && model.getSubImageList().getSubImageInfoObject() != null
				&& model.getSubImageList().getSubImageInfoObject().size() > 0) {
				face.setSubImageList(model.getSubImageList().getSubImageInfoObject());
			}

			try {
				if (face != null && StringUtils.isEmpty(face.getFaceID()) && face.getInfoKind() != null
					&& face.getInfoKind() == 1) {
					face.setFaceID(BussinessIDGennelUtil.createViewLibraryID(appId, fCode, true, cCode));
				} else {
					Face TBigDataPerson2 = iTBigDataFaceService.findByFaceID(face.getFaceID());
					if (TBigDataPerson2 != null) {
						setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数FaceID重复；");
						resps.add(status);
						continue;
					}
				}
				validateParams(face, status);
				if (status.getStatusCode().equals(VIIDRespEnum.OK.getCode())) {
					if (status.getStatusCode().equals(VIIDRespEnum.OK.getCode())) {
					Face tBigDataFace = BeanUtilss.transferObjectIgnoreCase(face, Face.class);
		//			iTBigDataFaceService.insert(tBigDataFace);
					iTBigDataFaceService.save(tBigDataFace);
					// 图片和业务对于关系
					saveImageBusiness(face.getSubImageList(), type, face.getFaceID());
					status.setId(face.getFaceID());
					status.setStatusString("新增成功；");
					}
				}
			} catch (Exception e) {
				setStatus(status, VIIDRespEnum.DEVICE_ERROR, "请联系管理员；");
				log.error(" TBigDataFaceController  postList  Exception {} ", e);
			}
			resps.add(status);
		}
    }

    /**
     * 批量修改
     *
     * @param param
     * @return
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     */
    @PutMapping(value = "/Faces", produces = "application/VIID+JSON")
    public Object putList(@RequestBody FaceBatchParam param) throws IOException {
	List<ResponseStatus> resps = new ArrayList<ResponseStatus>();
	if (param == null || param.getFaceListObject() == null || param.getFaceListObject().getFaceObject() == null
		|| param.getFaceListObject().getFaceObject().size() == 0) {
	    ResponseStatus status = new ResponseStatus(Urlconstant.URL_BIG_DATA_15, VIIDRespEnum.OK.getCode(),
		    new Date());
	    setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数为空；");
	    resps.add(status);
	    return BeanUtilss.getBatchResponseModel(resps);
	}
	List<FaceModel> list = param.getFaceListObject().getFaceObject();
	commonPutFaceBatchModel(resps, list);
	return BeanUtilss.getBatchResponseModel(resps);
    }

    public void commonPutFaceBatchModel(List<ResponseStatus> resps, List<FaceModel> list) {
	for (FaceModel model : list) {
	    ResponseStatus status = new ResponseStatus(Urlconstant.URL_BIG_DATA_15, VIIDRespEnum.OK.getCode(),
		    new Date());
	    if (model == null) {
		setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数为空；");
		resps.add(status);
		continue;
	    }
	    FaceBatch face = BeanUtilss.transferObjectCommon(model, FaceBatch.class);
	    if (model.getSubImageList() != null && model.getSubImageList().getSubImageInfoObject() != null
		    && model.getSubImageList().getSubImageInfoObject().size() > 0) {
		face.setSubImageList(model.getSubImageList().getSubImageInfoObject());
	    }
	    try {
		validateParams(face, status);
		if (status.getStatusCode().equals(VIIDRespEnum.OK.getCode())) {
		    updateCommon(face, status, face.getFaceID());
		}
	    } catch (Exception e) {
		setStatus(status, VIIDRespEnum.DEVICE_ERROR, "请联系管理员；");
		log.error(" TBigDataFaceController  putList  Exception {} ", e);
	    }
	    resps.add(status);
	}
    }

    /**
     * 批量删除
     *
     * @param IDList
     * @return
     */
    @DeleteMapping(value = "/Faces", produces = "application/VIID+JSON")
    public Object deleteList(@RequestParam("IDList") String IDList) {
	List<ResponseStatus> resps = new ArrayList<ResponseStatus>();
	if (StringUtils.isEmpty(IDList)) {
	    ResponseStatus status = new ResponseStatus(Urlconstant.URL_BIG_DATA_15, VIIDRespEnum.OK.getCode(),
		    new Date());
	    setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数IDList为空；");
	    resps.add(status);
	    return BeanUtilss.getBatchResponseModel(resps);
	}
	String[] ids = IDList.split(",");
	for (String id : ids) {
	    ResponseStatus status = new ResponseStatus(Urlconstant.URL_BIG_DATA_15, VIIDRespEnum.OK.getCode(),
		    new Date());
	    try {
		deleteCommon(status, id);
	    } catch (Exception e) {
		setStatus(status, VIIDRespEnum.DEVICE_ERROR, "请联系管理员；");
		log.error(" TBigDataFaceController  deleteList  Exception {} ", e);
	    }
	    resps.add(status);
	}
	return BeanUtilss.getBatchResponseModel(resps);
    }

    /**
     * 单个查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/Faces/{id}", produces = "application/VIID+JSON;charset=UTF-8")
    public Object get(@PathVariable("id") String id) {
        FaceBatch face = null;
	try {
	    Face tBigDataFace = iTBigDataFaceService.findByFaceID(id);
	    if (tBigDataFace != null && !StringUtils.isEmpty(tBigDataFace.getFaceID())) {
		face = BeanUtilss.transferObjectIgnoreCase(tBigDataFace, FaceBatch.class);
		List<SubImageInfoVo> volist = imageBusinessService
			.findSubImageInfoVo(tBigDataFace.getFaceID(), type);
		face.setSubImageList(volist);
	    }
	} catch (Exception e) {
	    log.error("TBigDataFaceController get Exception {}", e.getMessage());
	}
	if (face == null) {
	    return new ResponseEntity<Map<String, Object>>(new HashMap<String, Object>(), HttpStatus.NO_CONTENT);
	}
	FaceParam param = new FaceParam();
	FaceModel model = BeanUtilss.transferObjectCommon(face, FaceModel.class);
	if (face.getSubImageList() != null && face.getSubImageList().size() > 0) {
	    SubImageBatchParam subImageList = new SubImageBatchParam();
	    subImageList.setSubImageInfoObject(face.getSubImageList());
	    model.setSubImageList(subImageList);
	}
	param.setFaceObject(model);
	return param;
    }

    /**
     * 单个修改
     *
     * @param param
     * @param id
     * @return
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     */
    @PutMapping(value = "/Faces/{id}", produces = "application/VIID+JSON")
    public Object put(@RequestBody FaceParam param, @PathVariable("id") String id) throws IOException {
	ResponseStatus status = new ResponseStatus(Urlconstant.URL_BIG_DATA_14, VIIDRespEnum.OK.getCode(), new Date());
	if (param == null || param.getFaceObject() == null) {
	    setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数face无效，没有对于数据；");
	    return BeanUtilss.getResponseModel(status);
	}
	if (StringUtils.isEmpty(id)) {
	    setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数FaceID为空；");
	    return BeanUtilss.getResponseModel(status);
	}
	try {
	    FaceModel model = param.getFaceObject();
	    FaceBatch face = BeanUtilss.transferObjectCommon(model, FaceBatch.class);
	    if (model.getSubImageList() != null && model.getSubImageList().getSubImageInfoObject() != null
		    && model.getSubImageList().getSubImageInfoObject().size() > 0) {
		face.setSubImageList(model.getSubImageList().getSubImageInfoObject());
	    }
	    validateParams(face, status);
	    if (status.getStatusCode().equals(VIIDRespEnum.OK.getCode())) {
		updateCommon(face, status, id);
	    }
	} catch (Exception e) {
	    setStatus(status, VIIDRespEnum.DEVICE_ERROR, "请联系管理员；");
	}
	return BeanUtilss.getResponseModel(status);
    }

    /**
     * 单个删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/Faces/{id}", produces = "application/VIID+JSON")
    public Object delete(@PathVariable("id") String id) {
	ResponseStatus status = new ResponseStatus(Urlconstant.URL_BIG_DATA_14, VIIDRespEnum.OK.getCode(), new Date());
	if (StringUtils.isEmpty(id)) {
	    setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数FaceID为空；");
	    return BeanUtilss.getResponseModel(status);
	}
	try {
	    deleteCommon(status, id);
	} catch (Exception e) {
	    log.error("TBigDataFaceController delete Exception {}", e);
	    setStatus(status, VIIDRespEnum.DEVICE_ERROR, "请联系管理员；");
	}
	return BeanUtilss.getResponseModel(status);
    }

    public void deleteCommon(ResponseStatus status, String id) throws Exception {
	Face TBigDataFace2 = iTBigDataFaceService.findByFaceID(id);
	if (TBigDataFace2 == null) {
	    setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数FaceID无效，没有对于数据；");
	} else {
	    iTBigDataFaceService.deleteByFaceID(id);

	    // 删除 图片和业务对于关系
	    deleteImageBusiness(type, id);
	    status.setId(id);
	    status.setStatusString("删除成功；");
	}
    }

    public void updateCommon(FaceBatch face, ResponseStatus status, String id) throws Exception {
	Face TBigDataFace2 = iTBigDataFaceService.findByFaceID(id);
	if (TBigDataFace2 == null) {
	    setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数FaceID无效，没有对于数据");
	} else {
	    face.setId(TBigDataFace2.getId());
	    Face tBigDataFace = BeanUtilss.transferObjectIgnoreCase(face, Face.class);
	    iTBigDataFaceService.updateById(tBigDataFace);
	    // 图片和业务对于关系
	    saveImageBusiness(face.getSubImageList(), type, face.getFaceID());
	    status.setId(id);
	    status.setStatusString("修改成功");
	}
    }

    /**
     * 条件查询
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/Faces", produces = "application/VIID+JSON;charset=UTF-8")
    public Object getList(HttpServletRequest request) {
	Object attribute = request.getAttribute("map");
	FaceBatchParam param = null;
	if (attribute instanceof Map) {
	    Map<String, Object> map = (Map<String, Object>) attribute;
	    param = iTBigDataFaceService.getFaceList(map);
	}
	if (param == null) {
	    return new ResponseEntity<Map<String, Object>>(new HashMap<String, Object>(), HttpStatus.NO_CONTENT);
	}
	return param;
    }


    /**
     * 设置返回值代码和消息 VIID 标准
     *
     * @param res
     * @param e
     * @param field
     */
    protected void setStatus(ResponseStatus res, VIIDRespEnum e, String field) {
        StringBuffer sb = new StringBuffer();
        sb.append(e.getMsg() + "[" + field + "]");
        res.setStatusCode(e.getCode());
        res.setStatusString(sb.toString());
    }

    public void saveImageBusiness(List<SubImageInfoVo> subImageList, String type, String ywId) {
        if (subImageList != null && !subImageList.isEmpty()) {
            for (SubImageInfoVo vo : subImageList) {
                if (vo == null || StringUtils.isEmpty(vo.getImageID())) {
                    continue;
                }
                ImageBusiness tBigDataImageBusiness = new ImageBusiness();
                tBigDataImageBusiness.setImageId(vo.getImageID());
                tBigDataImageBusiness.setYwId(ywId);
                tBigDataImageBusiness.setBigType(type);
                tBigDataImageBusiness.setImageType(type);
                if ("01".equals(type)) {
                    if (!StringUtils.isEmpty(vo.getType()) && Arrays
                            .asList("01", "02", "03", "04", "05", "06", "07", "08", "09").contains(vo.getType())) {
                        tBigDataImageBusiness.setImageType(vo.getType());
                    }
                }
                // 先删除
                deleteImageBusiness(type, ywId);
                // 新增
                imageBusinessService.save(tBigDataImageBusiness);
            }
        }
    }

    public void deleteImageBusiness(String type, String ywId) {
        ImageBusiness tBigDataImageBusiness = new ImageBusiness();
        tBigDataImageBusiness.setYwId(ywId);
        tBigDataImageBusiness.setBigType(type);
        imageBusinessService.deleteImageBusiness(tBigDataImageBusiness);
    }

}
